import * as THREE from 'three';
import {
    OrbitControls
} from 'three/addons/controls/OrbitControls.js';
import {
    DRACOLoader
} from 'three/addons/loaders/DRACOLoader.js';
import {
    GLTFLoader
} from 'three/addons/loaders/GLTFLoader.js';
console.log(THREE);

(function () {
    console.log("首页文件");
    let now_open_diag = {}
    now_open_diag.API_URL = ' '
    document.getElementById("todayTimer").innerHTML = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    //创建一个三维场景
    const devicePixelRatio = window.devicePixelRatio; //设备分辨率
    let scene, light, spotLight, renderer, controls, camera, mesh

    //初始化场景元素
    const initCanvas = () => {
        initScene()
        initLight()
        initCamera()
        //initASphere()
        initSceneItems()
        initARenderer()
        initAControls()
    }
    let getshishi = null
    const getr = () => {
        clearInterval(getshishi)
        req.post('/api/sjdl/pub/get/option', {}).then(res => {
            res.code == 200 && res.result && set3DFloorColor(res.result)
            // res.result && res.result.dataList && res.result.dataList.length > 0 && initEventList(res.result.dataList)
            let list = document.querySelectorAll('.number_1');
            Number(res.data.dcsdata.jzgl).toFixed(0) == 0 && Number(res.data.dcsdata.ycfy).toFixed(0) != 0 ? "" : list[0].innerText = Number(res.data.dcsdata.jzgl).toFixed(1) + "MW"
            list[1].innerText = res.data.dcsdata.rlmzl + "t/h"
            list[2].innerText = res.data.dcsdata.yl + "%"
            list[3].innerText = res.data.dcsdata.ycfy + "KPa"
            list[4].innerText = res.data.dcsdata.noxnd + "Nm3"
            if (res.data.dcsdata.zqll === null) {
                list[4].innerText = 0 + "t/h"
            }
            list[5].innerText = res.data.dcsdata.yyqnox
            now_open_diag.floorModelList = res.data.floorModelList
            sessionStorage.setItem('glnumber', res.data.floorModelList.length)
            removeLoader('加载中....')
            getshishi = setInterval(() => { getr() }, 3000)
        })
    }
    const initScene = () => {
        scene = new THREE.Scene()
        // 场景设置
        // scene.background = new THREE.Color('#03244a')
        //在代码上面声明场景等下面加这句:
        //scene.fog = new THREE.Fog('#eee', 120, 150)
        //创建辅助坐标轴
        // const axesHelper = new THREE.AxesHelper(100)
        // scene.add(axesHelper)
        //加个地板 投射影子
        // let floorGeometry = new THREE.PlaneGeometry(50, 50,32, 32) //形状
        // let floorMaterial =new THREE.MeshStandardMaterial( {color: 0x03244a} );//材质
        // let floor = new THREE.Mesh(floorGeometry, floorMaterial)
        // floor.rotation.x = -0.5 * Math.PI
        // floor.receiveShadow = true
        // floor.position.y = -0.001
        // scene.add(floor)
    }

    //创建灯光
    const initLight = () => {
        // const ambient = new THREE.HemisphereLight( 0xffffff, 0x444444, 0.05 );
        light = new THREE.AmbientLight(0xffffff, 0.5); // soft white light
        scene.add(light);
        // 聚光灯
        spotLight = new THREE.SpotLight(0xffffff, 5);
        spotLight.position.set(25, 150, 75);
        spotLight.angle = Math.PI / 6;
        spotLight.penumbra = 1;
        spotLight.decay = 2;
        spotLight.distance = 300;
        // spotLight.map = textures[ 'disturb.jpg' ];
        spotLight.castShadow = true; //可以产生阴影
        spotLight.shadow.mapSize.width = 2048;
        spotLight.shadow.mapSize.height = 2048;
        spotLight.shadow.camera.near = 10;
        spotLight.shadow.camera.far = 200;
        spotLight.shadow.focus = 1;
        scene.add(spotLight);
    }

    //创建相机
    const initCamera = () => {
        //创建一个透视相机
        const width = document.getElementById('three').offsetWidth
        const height = document.getElementById('three').offsetHeight
        // console.log(width);
        camera = new THREE.PerspectiveCamera(80, width / height, 1, 3000)
        //设置相机位置
        //x 轴红色  y绿色  z  蓝色
        camera.position.set(0, 0, 7.5)
        // camera.position.set(200, 200, 200);
        // camera.layers.disableAll();
        // camera.layers.enableAll();
        // camera.layers.disable( 1);
        // camera.layers.enable( 1);
        //设置相机方向
        // camera.lookAt(0,-5,0)
        //创建助手
        // const helper = new THREE.CameraHelper( spotLight.shadow.camera );
        // scene.add( helper );
    }

    //创建场景元素
    const initSceneItems = () => {
        const gltfLoader2 = new GLTFLoader();
        var dracoLoader = new DRACOLoader();
        // dracoLoader.setDecoderPath( '/js/draco/' );
        dracoLoader.setDecoderPath('/examples/js/libs/draco/');
        gltfLoader2.setDRACOLoader(dracoLoader);
        const url2 = './guolu.glb';
        gltfLoader2.load(url2, (gltf) => {
            const root = gltf.scene;
            console.log(root.children);
            // 给每个mesh 添加阴影
            root.traverse(function (node) {
                if (node instanceof THREE.Mesh) {
                    node.castShadow = true;
                }
            });
            mesh = root
            //纹理贴图加载器TextureLoader
            // const texLoader = new THREE.TextureLoader();
            // // .load()方法加载图像，返回一个纹理对象Texture
            // const texturei = texLoader.load('./assets/a.png');
            // const materiali = new THREE.MeshLambertMaterial({
            //     // 设置纹理贴图：Texture对象作为材质map属性的属性值
            //     map: texturei, //map表示材质的颜色贴图属性
            // });

            // mesh.children[4].material.map=texture
            // mesh.children[4].material.opacity = 0.4
            // mesh.children[4].material.transparent = true
            // mesh.children[5].material.transparent = true
            mesh.children[7].material.transparent = true
            mesh.children[7].material.opacity = mesh.children[8].material.opacity = 0.5
            mesh.children[8].material.transparent = true
            // mesh.children[1].material.transparent = true
            // mesh.children[2].material.transparent = true
            // mesh.children[5].material.opacity = 0.2
            // mesh.children[1].material.opacity = 0.5
            /*
            // mesh.children[5].geometry =
            mesh.children[6].material = materiali
            mesh.children[7].material = materiali
            mesh.children[8].visible = false
            mesh.children[9].material = materiali
            mesh.children[10].material = materiali
            mesh.children[11].material = materiali
            mesh.children[12].material = materiali
            mesh.children[13].material = materiali*/
            mesh.children[18].visible = false
            mesh.children[23].visible = false
            mesh.children[0].position.y = -2
            mesh.children[9].position.y = -1.2
            mesh.children[16].position.y = -1.2
            mesh.children[23].position.y = -1.2
            mesh.position.y = -1.7
            mesh.position.x = 0
            mesh.position.z = 0
            mesh.rotation.y = 0
            mesh.castShadow = true; //有阴影
            // mesh.scale.set(0.2,0.2,0.2);
            //console.log(mesh); //group
            scene.add(mesh);
            sessionStorage.setItem('glnumber', 4)
            if (sessionStorage.getItem('glnumber') == 4) {
                mesh.children[1].visible = mesh.children[10].visible = mesh.children[17].visible = mesh.children[24].visible = false
                mesh.children[2].visible = mesh.children[11].visible = mesh.children[18].visible = mesh.children[25].visible = false
            } else if (sessionStorage.getItem('glnumber') == 5) {
                mesh.children[1].visible = mesh.children[10].visible = mesh.children[17].visible = mesh.children[24].visible = false
            }

        },
            // 加载过程回调函数onProgress：加载过程不停地重复执行该函数中代码
            function (xhr) {
                // 控制台查看加载进度xhr
                // 通过加载进度xhr可以控制前端进度条进度   Math.floor:小数加载进度取整
                //console.log('加载进度' + Math.floor(xhr.loaded / xhr.total * 100) + '%');
            },
            // 加载错误回调函数onError
            function (err) {
                console.error('加载发生错误');
            }
        );
    }
    //创建渲染
    const initARenderer = () => {
        renderer = new THREE.WebGLRenderer({
            antialias: true,
            logarithmicDepthBuffer: true,
            alpha: true,
        });
        // renderer.setPixelRatio (devicePixelRatio)
        renderer.setPixelRatio(window.devicePixelRatio);
        // console.log(document.getElementById('three').offsetWidth);
        renderer.setSize(document.getElementById('three').offsetWidth, document.getElementById('three').offsetHeight);
        renderer.shadowMap.enabled = true;
        renderer.shadowMap.type = THREE.PCFSoftShadowMap;
        // renderer.outputEncoding = THREE.sRGBEncoding;
    }
    const render = () => {
        // console.log(renderer);
        renderer.render(scene, camera)
        // labelRenderer.render( scene, camera )
        controls.update();
        requestAnimationFrame(render);
    }
    window.addEventListener('resize', onWindowResize);

    function onWindowResize() {
        camera.aspect = document.getElementById('three').offsetWidth / document.getElementById('three').offsetHeight;
        camera.updateProjectionMatrix();
        renderer.setSize(document.getElementById('three').offsetWidth, document.getElementById('three').offsetHeight);
        // labelRenderer.setSize(document.getElementById('three').offsetWidth, document.getElementById('three').offsetHeight );
        // labelRenderer.render( scene, camera )
        // renderer.render(scene, camera)

    }
    //创建相机控制器
    const initAControls = () => {
        // controls.enableDamping = true
        // 设置阻尼

        //controls = new TrackballControls(camera, document.querySelector('#three'));
        // controls.noZoom = true;
        // console.log(controls);
        //controls.noPan = true;
        // controls.handleResize();
        controls = new OrbitControls(camera, document.querySelector('#three'))
        //controls = new OrbitControls(camera, renderer.domElement)
        controls.update();
        controls.autoRotate = true
        // controls.enableDamping = true;
        controls.autoRotateSpeed = 1;
        // controls.enableRotate=false
        // controls.enablePan=false  //右键平移
        //
        // controls.maxAzimuthAngle=0
        // controls.minAzimuthAngle=0
        // controls.maxPolarAngle=0
        // controls.minPolarAngle=0

        // controls.addEventListener('change',()=>{
        //   console.log('change');
        //   renderer.render(scene, camera)
        // // labelRenderer.render( scene, camera )
        //
        // })
    }
    initCanvas()
    // console.log(renderer.domElement);
    document.getElementById('three')?.appendChild(renderer.domElement)
    render()
    //createSpriteText()
    let oIndexDiv = document.getElementById("index_rsszhjk")
    let initDataFromINnputshishi = null
    const initDataFromINnput = () => {
        clearInterval(initDataFromINnputshishi)
        //console.log(rsqState);
        req.get('/api/sjdl/home/point/value').then(res => {
            let tablenumber = []
            Array(tablenumber)
            let tablebox = []
            //重置数据
            console.log(res);
            // 获取输入框值  5 6  8 9  11 12  14 15  17 18  20 21   23 24

            let str = ""
            for (let key in res.data) {
                tablebox.push({
                    label: res.data[key], // label 字段
                    value: key // value字段
                })
            }
            tablebox.sort(function (a, b) {
                return (a.value + '').localeCompare(b.value + '')
            })
            for (let i = 0; i < tablebox.length; i++) {
                tablenumber.push({
                    nameber: tablebox[i].label.TR.toFixed(0),
                    value: tablebox[i].label.warnData
                })
            }
            for (let i = 0; i < tablebox.length; i++) {
                tablenumber.push({
                    nameber: tablebox[i].label.ZHJL.toFixed(0),
                    value: tablebox[i].label.warnData
                })
            }
            for (let i = 0; i < tablebox.length; i++) {
                tablenumber.push({
                    nameber: tablebox[i].label.RSWDX.toFixed(0),
                    value: tablebox[i].label.warnData
                })
            }
            for (let index = 0; index < 3; index++) {
                // console.log(index);
                str += '<p><span style="color:#343434">' + (index == 0 ? '温度(°C)' : index == 1 ? '着火距离(mm)' : index == 2 ? '燃烧稳定性(%)' : "") + '</span>'
                for (let i = 0; i < 16; i++) { //i < 24
                    let irsqState = i < 4 ? 0 : i > 3 && i < 8 ? 1 : i > 7 && i < 12 ? 2 : i > 11 && i < 16 ? 3 : i > 15
                    let startId = index * 16

                    // let nowValue = Number(document.getElementById(startId + 4 + "").value).toFixed(0)
                    let nowValue = Number(tablenumber[startId + i].nameber)
                    let level_1 = Number(tablenumber[startId + i].value.tempLowLower)
                    let level_2 = Number(tablenumber[startId + i].value.tempLower)
                    let level_3 = Number(tablenumber[startId + i].value.tempUpUpper)
                    let level_4 = Number(tablenumber[startId + i].value.tempUpper)
                    let level_5 = Number(tablenumber[startId + i].value.distinceLowLower)
                    let level_6 = Number(tablenumber[startId + i].value.distinceLower)
                    let level_7 = Number(tablenumber[startId + i].value.distinceUpUpper)
                    let level_8 = Number(tablenumber[startId + i].value.distinceUpper)
                    let level_9 = Number(tablenumber[startId + i].value.stabilityLowLower)
                    let level_10 = Number(tablenumber[startId + i].value.stabilityLower)
                    if (rsqState[irsqState] == 1) { //停磨
                        if (index == 0 && Number(nowValue) > 1450) { //温度大于1450 标红
                            str += '<span style="color:red;width:100px">' + nowValue + '</span>'
                        } else if (index > 0) {
                            str += '<span style="color:#1e901e;width:100px">' + '0' + '</span>'

                        } else {
                            str += '<span style="color:#1e901e;width:100px">' + nowValue + '</span>'
                        }

                    } else {
                        if (index == 0) {
                            if (level_3 <= nowValue || nowValue <= level_1) {
                                str += '<span style="color:red;width:100px">' + nowValue + '</span>'
                            } else if (level_1 <= nowValue && nowValue <= level_4) {
                                str += '<span style="color:#1e901e;width:100px">' + nowValue + '</span>'
                            } else if (level_1 <= nowValue && nowValue <= level_2 || level_4 <= nowValue && nowValue <= level_3) {
                                str += '<span style="color:yellow;width:100px">' + nowValue + '</span>'
                            }
                        } else if (index == 1) {
                            if (nowValue == 0) {
                                str += '<span style="color:#1e901e;width:100px">' + nowValue + '</span>'
                            }
                            else if (level_7 <= nowValue || nowValue <= level_5) {
                                str += '<span style="color:red;width:100px">' + nowValue + '</span>'
                            } else if (level_5 <= nowValue && nowValue <= level_8) {
                                str += '<span style="color:#1e901e;width:100px">' + nowValue + '</span>'
                            } else if (level_5 <= nowValue && nowValue <= level_6 || level_8 <= nowValue && nowValue <= level_7) {
                                str += '<span style="color:yellow;width:100px">' + nowValue + '</span>'
                            }
                        } else {
                            if (nowValue == 0) {
                                str += '<span style="color:#1e901e;width:100px">' + nowValue + '</span>'
                            }
                            else if (nowValue <= level_9) {
                                str += '<span style="color:red;width:100px">' + nowValue + '</span>'
                            } else if (nowValue >= level_10) {
                                str += '<span style="color:#1e901e;width:100px">' + nowValue + '</span>'
                            } else if (level_9 <= nowValue && nowValue <= level_10) {
                                str += '<span style="color:yellow;width:100px">' + nowValue + '</span>'
                            }
                        }
                    }
                }
                str += '</p>'
            }
            oIndexDiv.innerHTML = str
            initDataFromINnputshishi = setInterval(() => { initDataFromINnput() }, 3000)
        })
    }
    
    const initEventList = (arr) => {
        let oIndexDiv = document.getElementById("indexEventList")
        let str = ""
        for (let index = 0; index < arr.length; index++) {
            str += '<p><span>' + arr[index].createDate + '</span><span>' + arr[index].eventName.split("! ")[0] + '</span></p>'
        }
        oIndexDiv.innerHTML = str
    }
    const initEvent = (str) => { //
        //获取事件元素
        let oFootBtns = document.getElementById(str).children //底部菜单 btns
        if (str == "zbf_foot_btns") {
            now_open_diag.username == "admin" ? "" : oFootBtns[oFootBtns.length - 1].style.display = "none"
            // now_open_diag.username == "admin" ? "" : oFootBtns[oFootBtns.length - 2].style.display = "none"
        }
        for (let i = 0; i < oFootBtns.length; i++) {
            oFootBtns[i].onclick = () => {
                for (let ii = 0; ii < oFootBtns.length; ii++) {
                    oFootBtns[ii].className = ""
                }
                oFootBtns[i].className = "active"
                if (str == "zbf_r_btns") {
                    if (i == 8) {
                        for (let o = 6; o < 14; o++) {
                            scene.children[2].children[o].visible = false
                        }
                    } else {
                        scene.children[2].children[13 - i].visible = !scene.children[2].children[13 - i].visible
                    }
                } else {
                    const exit3D = () => {
                        mesh.children.forEach(item => {
                            //console.log(item.type);
                            if (item.type == "Mesh") {
                                item.geometry.dispose()
                                item.material.map ? item.material.map.dispose() : ""
                                item.material.dispose()
                            }

                        });
                        scene.remove(mesh)
                    }

                    function closeDiag() {
                        scene ? (exit3D(), scene = light = spotLight = renderer = controls = camera = null) : ''
                        timer ? clearInterval(timer) : ""
                        oTodayTimer ? clearInterval(oTodayTimer) : ""
                        window.removeEventListener('resize', onWindowResize);
                        // var tab_titlenodes = document.getElementsByClassName('ls_tabtitle')[0].getElementsByTagName('li');
                        // onCloseTab(tab_titlenodes[now_open_diag.index].childNodes[1].childNodes[0])
                    }
                    switch (i) {
                        case 0:
                            closeDiag()
                            setTimeout(() => {
                                window.location.href = "/index.html"
                            }, 200)
                            break;
                        case 1:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("全炉膛温度场", 11, "SJDL_IFS_DATA.prj", "全炉膛温度场")
                                window.location.href = "/quanlutang.html"
                            }, 200)

                            break;
                        case 2:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("横截面", 6, "SJDL_IFS_DATA.prj", "横截面")
                                window.location.href = "/hjm.html"
                            }, 200)

                            break;
                        case 3:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("燃烧稳定性监测", 7, "SJDL_IFS_DATA.prj", "燃烧稳定性监测")
                                window.location.href = "/ranshaowendingxing.html"
                            }, 200)

                            break;
                        case 4:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("煤粉分配率", 9, "SJDL_IFS_DATA.prj", "煤粉分配率")
                                window.location.href = "/meifen.html"
                            }, 200)

                            break;
                        case 5:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("煤粉颗粒度分布", 8, "SJDL_IFS_DATA.prj", "煤粉颗粒度分布")
                                window.location.href = "/main/dcimgs/gl/main.html"
                            }, 200)

                            break;
                        case 6:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("预警信息", 12, "SJDL_IFS_DATA.prj", "预警信息")
                                window.location.href = "/yujing.html"
                            }, 200)

                            break;
                        case 7:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("历史数据", 10, "SJDL_IFS_DATA.prj", "历史数据")
                                window.location.href = "/history.html"
                            }, 200)

                            break;
                        case 8:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("历史数据", 10, "SJDL_IFS_DATA.prj", "历史数据")
                                window.location.href = "/dcsHistory.html"
                            }, 200)
                            break;
                        case 9:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("预警阈值配置修改", 14, "SJDL_IFS_DATA.prj", "预警阈值配置修改")
                                window.location.href = "/canshushezhi.html"
                            }, 200)

                            break;
                        default:

                    }

                }
            }
        }
    }
    initEvent('zbf_foot_btns') //底部菜单 btns

    function Request(baseUrl = '', time = 1000) {
        this.baseUrl = baseUrl;

        function request(url, option = {}) {
            return new Promise(async (resolve, reject) => {
                try {
                    const response = await fetch(baseUrl + url, option);
                    if (response.status == '200') {
                        const data = await response.json();
                        if (data.code == '200') {
                            resolve(data);
                        } else {
                            reject(data.message || '请求失败');
                        }
                    } else {
                        reject(response);
                    }
                } catch (e) {
                    reject(e);
                }
            })
        }

        this.post = function (url, data) {
            return request(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
        }

        this.get = function (url) {
            return request(url, {
                method: 'GET'
            })
        }
    }
    Request.createRequest = function (baseUrl) {
        return new Request(baseUrl);
    }
    const req = Request.createRequest(now_open_diag.API_URL);

    let getdatashishi = null
    const getData = () => {
        clearInterval(getdatashishi)
        // 初始化表单数据
        let obj = {
            // startDate: moment(new Date()).format('YYYY/MM/DD') + " 00:00:01",
            // endDate: moment(new Date()).format('YYYY/MM/DD') + " 23:59:59",
            pageNum: 1,
            pageSize: 6
        }
        req.post('/spf/visit/getEventPage', obj).then(res => {

            res.data && res.data.list && res.data.list.length > 0 && initEventList(res.data.list)
            getdatashishi = setInterval(() => { getData() }, 3000)
        })

    }


    let rsqState = ["", "", "", ""]
    let dshishi = null
    const get3DFloorColor = () => { //锅炉每层燃烧器温度及燃烧状态
        clearInterval(dshishi)
        req.post('/spf/visit/getThermalFieldAll').then(res => {
            rsqState[0] = res.data.runStateA
            rsqState[1] = res.data.runStateB
            rsqState[2] = res.data.runStateC
            rsqState[3] = res.data.runStateD
            res.code == 200 && res.result && set3DFloorColor(res.result)
            //box = '20'
            const myStyles = `display: none;`;
            const element = document.querySelectorAll("span[class$='ee']");
            for (let i = 0; i < element.length; i++) {
                element[i].style.cssText = myStyles
            }
            const element1 = document.querySelectorAll("span[class$='ff']");
            for (let i = 0; i < element1.length; i++) {
                element1[i].style.cssText = myStyles
            }
            dshishi = setInterval(() => { get3DFloorColor() }, 3000)
        })
    }

    const set3DFloorColor = (obj) => {
        // 12-17 sofa -a 操作透明度 停磨需隐藏
        // 18-23  sofa -a 蓝色风  停磨需隐藏
        let nameArr = ["A", "B", "C", "D", "E", "SOFA"]
        for (let index = 0; index < nameArr.length; index++) {
            const element = nameArr[index];
            if (obj[`runState${nameArr[index]}`] == 1) {
                scene.children[2].children[17 - index].material.opacity = 1
                scene.children[2].children[23 - index].visible = false
            } else {

                let newTemp = obj[`centerTemp${nameArr[index]}`] > 1800 ? 1800 : obj[`centerTemp${nameArr[index]}`] < 1500 ? 1500 : obj[`centerTemp${nameArr[index]}`]
                scene.children[2].children[17 - index].material.opacity = newTemp == 0 ? 1 : ((1800 - newTemp) / 300).toFixed(2)
                index == 5 ? "" : scene.children[2].children[23 - index].visible = true
                // console.log(scene.children[2].children[17-index].name,scene.children[2].children[17].material.opacity);
            }

        }


    }

    lsLoader('加载中....')
    let timer = setTimeout(() => {
        get3DFloorColor()
        getData()
        getr()
        initDataFromINnput()
    }, 500)
    let oTodayTimer = setInterval(() => {
        document.getElementById("todayTimer").innerHTML = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    }, 1000)
})()
